#!/bin/bash

set -e

if ! getent group ebox-usercorner > /dev/null 2>&1
then
    addgroup --system ebox-usercorner
fi
if ! getent passwd ebox-usercorner > /dev/null 2>&1
then
    adduser --system --home /var/lib/zentyal-usercorner/ \
        --disabled-password --ingroup ebox-usercorner ebox-usercorner
fi

# setup logs directory
USER=ebox-usercorner
GROUP=ebox-usercorner
LOGS_DIR=/var/log/zentyal-usercorner
test -d $LOGS_DIR || mkdir $LOGS_DIR
chmod 750 $LOGS_DIR
LOG_FILES="$LOGS_DIR/zentyal.log $LOGS_DIR/access.log $LOGS_DIR/error.log"
touch -a $LOG_FILES
chmod 750 $LOG_FILES
chown -R $USER.$GROUP $LOGS_DIR

# create user session ids and conf directories
test -d /var/lib/zentyal-usercorner/conf/ || mkdir -p /var/lib/zentyal-usercorner/conf/
test -d /var/lib/zentyal-usercorner/sids/ || mkdir -p /var/lib/zentyal-usercorner/sids/
chown -R ebox-usercorner:ebox-usercorner /var/lib/zentyal-usercorner

# Setup random redis password
REDIS_PASS="/var/lib/zentyal-usercorner/conf/redis.passwd"
if [ ! -f $REDIS_PASS ]; then
    touch $REDIS_PASS
    chmod 0660 $REDIS_PASS
    tr -dc A-Za-z0-9 < /dev/urandom | head -c10 > $REDIS_PASS
fi
chown ebox-usercorner:ebox $REDIS_PASS

# create ebox user corner HTTP server certificates
/usr/share/zentyal/create-certificate /var/lib/zentyal-usercorner/ssl > /dev/null 2>&1 || true
chown -R ebox-usercorner:ebox /var/lib/zentyal-usercorner/ssl
